// ProjectName: go-learn-demo
// PackageName: _1_elastic
// Description: 使用低级的API创建客户端
// Author: hy.bai
// Date: 2025-09-01 星期一 10:42

package elasticybxb

import (
	"crypto/tls"
	"fmt"
	"io"
	"log/slog"
	"net/http"
	"os"

	"github.com/elastic/go-elasticsearch/v8"
)

var LowInitElastic lowInitElastic

type lowInitElastic struct {
}

func (*lowInitElastic) InitElasticByUsername() (*elasticsearch.Client, error) {
	// 注意：配置xpack.security.http.ssl.enabled=false时，可以通过http协议进行API访问呢额
	// 创建Elasticsearch客户端
	cfg := elasticsearch.Config{
		Addresses: []string{
			ELASTIC_URL,
		},
		Username: ELASTIC_USER,
		Password: ELASTIC_PASSWORD,
		// 忽略证书, 否则会报错
		Transport: &http.Transport{
			TLSClientConfig: &tls.Config{InsecureSkipVerify: true},
		},
	}
	// 低级的API创建客户端
	client, err := elasticsearch.NewClient(cfg)
	if err != nil {
		slog.Error(fmt.Sprintf("Elastic Init Error: %s", err.Error()))
		return nil, err
	}
	return client, nil
}

func (*lowInitElastic) InitElasticByAPIKey() (*elasticsearch.Client, error) {
	cfg := elasticsearch.Config{
		Addresses: []string{
			ELASTIC_URL,
		},
		APIKey: ELASTIC_APIKEY,
		// 忽略证书, 否则会报错
		Transport: &http.Transport{
			TLSClientConfig: &tls.Config{InsecureSkipVerify: true},
		},
	}
	// 创建Elasticsearch客户端
	client, err := elasticsearch.NewClient(cfg)
	if err != nil {
		slog.Error(fmt.Sprintf("Elastic Init Error: %s", err.Error()))
		return nil, err
	}
	return client, nil
}

func (*lowInitElastic) InitElasticByCA() (*elasticsearch.Client, error) {
	caCert, caErr := os.ReadFile("11_elastic/certs/http_ca.crt")
	if caErr != nil {
		slog.Error(fmt.Sprintf("读取CA证书文件失败,原因是:%s", caErr.Error()))
	}
	cfg := elasticsearch.Config{
		Addresses: []string{
			ELASTIC_URL,
		},
		APIKey: ELASTIC_APIKEY,
		CACert: caCert,
	}
	// 创建Elasticsearch客户端
	client, err := elasticsearch.NewClient(cfg)
	if err != nil {
		slog.Error(fmt.Sprintf("Elastic Init Error: %s", err.Error()))
		return nil, err
	}
	return client, nil
}

func TestLowElasticConn() {
	client, err := LowInitElastic.InitElasticByUsername()
	if err != nil {
		slog.Error(fmt.Sprintf("Elastic Init Error: %s", err.Error()))
		return
	}
	// 使⽤Elasticsearch客户端进⾏操作...
	response, infoErr := client.Info()
	if infoErr != nil {
		slog.Error(fmt.Sprintf("Elastic Info Error: %s", infoErr.Error()))
		return
	}
	// 打印获取elasticsearch集群
	code := response.StatusCode
	fmt.Println("状态码:", code)
	data, _ := io.ReadAll(response.Body)
	fmt.Println(string(data))
}
